package com.example.sunmiv1.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.ClassificationAdapter;
import com.example.sunmiv1.adapter.OneLevelAdapter;
import com.example.sunmiv1.adapter.ParentAdapter;
import com.example.sunmiv1.adapter.TwoExpandAdapter;
import com.example.sunmiv1.entity.ChildEntity;
import com.example.sunmiv1.entity.ClassificationBean;
import com.example.sunmiv1.entity.ClassifyInfo;
import com.example.sunmiv1.entity.ParentEntity;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClassificationActivity extends Activity implements ExpandableListView.OnGroupExpandListener, ParentAdapter.OnChildTreeViewClickListener {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.classification_search_edit)
    EditText classificationSearchEdit;
    @BindView(R.id.classification_search_tv)
    TextView classificationSearchTv;
//    @BindView(R.id.classification_listView)
//    ListView classificationListview;

    private static final String TAG = "ClassificationActivity";
    @BindView(R.id.eList)
    ExpandableListView eList;
    @BindView(R.id.classify_one_listView)
    ListView classifyOneListView;
    @BindView(R.id.two_expandableListView)
    ExpandableListView twoExpandableListView;
    @BindView(R.id.classification_spinner)
    Spinner classificationSpinner;
    private Context context;
    private List<ClassificationBean.GoodscateBean> list = new ArrayList<>();
    private ClassificationBean classificationBean;
    private ClassificationAdapter classificationAdapter;
    private Intent intent;
    private ACache aCache;
    private LoadingDialog loadingDialog;

    private ClassifyInfo classifyInfo;
    private ArrayList<ParentEntity> parents;
    private ParentAdapter parentAdapter;
    private List<ClassificationBean.GoodscateBean.ChildBeanX.ChildBean> kindList = new ArrayList<>();


    private int type = 1; //1.三級 2.兩級 3.一級
    private List<String> spinnerList = new ArrayList<>();

    private List<ClassificationBean.GoodscateBean.ChildBeanX> childOneList = new ArrayList<>();
    private List<ClassificationBean.GoodscateBean.ChildBeanX.ChildBean> childTowList = new ArrayList<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    /*list.clear();
                    for (int i = 0; i < classificationBean.getGoodscate().size(); i++) {
                        list.add(classificationBean.getGoodscate().get(i));
                    }*/
                    if (type == 1) { //三級分類
                        parents = new ArrayList<>();
                        for (int i = 0; i < classificationBean.getGoodscate().size(); i++) {
                            ParentEntity parent = new ParentEntity();
                            parent.setGroupName(classificationBean.getGoodscate().get(i).getClass_name());
                            parent.setGroupColor(getResources().getColor(R.color.text_333));

                            ArrayList<ChildEntity> childs = new ArrayList<>();
                            for (int j = 0; j < classificationBean.getGoodscate().get(i).getChild().size(); j++) {
                                ChildEntity child = new ChildEntity();
                                child.setGroupName(classificationBean.getGoodscate().get(i).getChild().get(j).getClass_name());
                                child.setGroupColor(Color.parseColor("#333333"));
                                ArrayList<String> childNames = new ArrayList<>();
                                ArrayList<Integer> childColors = new ArrayList<>();
                                for (int k = 0; k < classificationBean.getGoodscate().get(i).getChild().get(j).getChild().size(); k++) {
                                    childNames.add(classificationBean.getGoodscate().get(i).getChild().get(j).getChild().get(k).getClass_name());
                                    childColors.add(Color.parseColor("#333333"));
                                }
                                child.setChildNames(childNames);
                                childs.add(child);
                            }
                            parent.setChilds(childs);
                            parents.add(parent);
                        }
                        setExpandableAdapter();
                    } else if (type == 2) {
                        //兩級分類
                        for (int i = 0; i < classificationBean.getGoodscate().size(); i++) {
                            for (int j = 0; j < classificationBean.getGoodscate().get(i).getChild().size(); j++) {
                                childOneList.add(classificationBean.getGoodscate().get(i).getChild().get(j));
                            }
                        }
                        setTwoExpandAdapter();
                    } else if (type == 3) {
                        kindList.clear();
                        for (int i = 0; i < classificationBean.getGoodscate().size(); i++) {
                            for (int j = 0; j < classificationBean.getGoodscate().get(i).getChild().size(); j++) {
                                for (int k = 0; k < classificationBean.getGoodscate().get(i).getChild().get(j).getChild().size(); k++) {
                                    kindList.add(classificationBean.getGoodscate().get(i).getChild().get(j).getChild().get(k));
                                }
                            }
                        }
                        setOneListView();
                    }
//                    setClassificationAdapter();
                    break;
                case 2:
                    loadingDialog.dismiss();
                    Toast.makeText(context, classificationBean.getMsg(), Toast.LENGTH_SHORT).show();
//                    setClassificationAdapter();
                    break;

                case 3: //獲取分類成功
                    loadingDialog.dismiss();
                    /*if (type == 1) { //三級分類
                        parents = new ArrayList<>();
                        for (int i = 0; i < classifyInfo.getGoodscate().size(); i++) {
                            ParentEntity parent = new ParentEntity();
                            parent.setGroupName(classifyInfo.getGoodscate().get(i).getClass_name());
                            parent.setGroupColor(getResources().getColor(R.color.text_333));

                            ArrayList<ChildEntity> childs = new ArrayList<>();
                            Log.e(TAG, "handleMessage: child1Size" + classifyInfo.getGoodscate().get(i).getChildone().size());
                            for (int j = 0; j < classifyInfo.getGoodscate().get(i).getChildone().size(); j++) {
                                ChildEntity child = new ChildEntity();
                                child.setGroupName(classifyInfo.getGoodscate().get(i).getChildone().get(j).getClass_name());
                                child.setGroupColor(Color.parseColor("#333333"));
                                ArrayList<String> childNames = new ArrayList<>();
                                ArrayList<Integer> childColors = new ArrayList<>();
                                Log.e(TAG, "handleMessage: child2Size" + classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().size());
                                for (int k = 0; k < classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().size(); k++) {
                                    childNames.add(classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().get(k).getClass_name());
                                    childColors.add(Color.parseColor("#333333"));
                                }
                                child.setChildNames(childNames);
                                childs.add(child);
                            }
                            parent.setChilds(childs);
                            parents.add(parent);
                        }
                        setExpandableAdapter();
                    } else if (type == 2) {
                        //兩級分類
                        for (int i = 0; i < classifyInfo.getGoodscate().size(); i++) {
                            for (int j = 0; j < classifyInfo.getGoodscate().get(i).getChildone().size(); j++) {
                                childOneList.add(classifyInfo.getGoodscate().get(i).getChildone().get(j));
                                *//*for (int k = 0; k < classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().size(); k++) {
                                    childTowList.add(classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().get(k));
                                }*//*
                            }
                        }
                        setTwoExpandAdapter();
                    } else if (type == 3) {
                        kindList.clear();
                        for (int i = 0; i < classifyInfo.getGoodscate().size(); i++) {
                            for (int j = 0; j < classifyInfo.getGoodscate().get(i).getChildone().size(); j++) {
                                for (int k = 0; k < classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().size(); k++) {
                                    kindList.add(classifyInfo.getGoodscate().get(i).getChildone().get(j).getChildtwo().get(k));
                                }
                            }
                        }
                        setOneListView();
                    }*/
                    break;
                case 4:
                    loadingDialog.dismiss();
                    break;
            }
        }
    };

    private TwoExpandAdapter twoExpandAdapter;

    /**
     * 二級分類
     */
    private void setTwoExpandAdapter() {
        twoExpandAdapter = new TwoExpandAdapter(context, childOneList);
        twoExpandableListView.setAdapter(twoExpandAdapter);
        twoExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int i) {
                if (childOneList.get(i).getChild().size() == 0) {
//                    Toast.makeText(context, "子類" + i, Toast.LENGTH_SHORT).show();
                    intent = new Intent(context, AddGoodsActivity.class);
                    intent.putExtra("name", childOneList.get(i).getClass_name());
                    intent.putExtra("id", childOneList.get(i).getId());
                    setResult(1, intent);
                    finish();
                }
            }
        });

        twoExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
//                Toast.makeText(context, "父類" + i1, Toast.LENGTH_SHORT).show();
                intent = new Intent(context, AddGoodsActivity.class);
                intent.putExtra("name", childOneList.get(i).getChild().get(i1).getClass_name());
                intent.putExtra("id", childOneList.get(i).getChild().get(i1).getId());
                setResult(1, intent);
                finish();
                return false;
            }
        });
    }

    private OneLevelAdapter oneLevelAdapter;

    private void setOneListView() {
        oneLevelAdapter = new OneLevelAdapter(context, kindList);
        classifyOneListView.setAdapter(oneLevelAdapter);
        classifyOneListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Toast.makeText(context, kindList.get(i).getId(), Toast.LENGTH_SHORT).show();
                intent = new Intent(context, AddGoodsActivity.class);
                intent.putExtra("name", kindList.get(i).getClass_name());
                intent.putExtra("id", kindList.get(i).getId());
                setResult(1, intent);
                finish();
            }
        });
    }

    private void setExpandableAdapter() {
        /**
         * 一級分類
         * */
        eList.setOnGroupExpandListener(this);
        parentAdapter = new ParentAdapter(context, parents);
        eList.setAdapter(parentAdapter);
        parentAdapter.setOnChildTreeViewClickListener(this);
        parentAdapter.onClicked(new ParentAdapter.onListener() {
            @Override
            public void getPosition(int position) {
                Log.e(TAG, "onGroupExpand: ==activity回調");
//                Toast.makeText(context, "父類" + position, Toast.LENGTH_SHORT).show();
//                Log.e(TAG, "getPosition: " + classifyInfo.getGoodscate().get(position).getId());
                intent = new Intent(context, AddGoodsActivity.class);
                intent.putExtra("name", classificationBean.getGoodscate().get(position).getClass_name());
                intent.putExtra("id", classificationBean.getGoodscate().get(position).getId());
                setResult(1, intent);
                finish();
            }

            @Override
            public void getPositionTwo(int groupPosition, int childPosition) {
//                Toast.makeText(context, "組:" + groupPosition + " 子項+" + childPosition, Toast.LENGTH_SHORT).show();
//                Log.e(TAG, "getPositionTwo: " + classifyInfo.getGoodscate().get(groupPosition).getChildone().get(childPosition).getId());
                intent = new Intent(context, AddGoodsActivity.class);
                intent.putExtra("name", classificationBean.getGoodscate().get(groupPosition).getChild().get(childPosition).getClass_name());
                intent.putExtra("id", classificationBean.getGoodscate().get(groupPosition).getChild().get(childPosition).getId());
                setResult(1, intent);
                finish();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_classification);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.classification1);
        spinnerList.add(getString(R.string.classification2));
        spinnerList.add(getString(R.string.classification3));
        spinnerList.add(getString(R.string.classification4));
        setSpinnerAdapter();
//        initData();
        classificationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                kindList.clear();
                childOneList.clear();
                type = position + 1;
                if (type == 1) {
                    eList.setVisibility(View.VISIBLE);
                    twoExpandableListView.setVisibility(View.GONE);
                    classifyOneListView.setVisibility(View.GONE);
                } else if (type == 2) {
                    eList.setVisibility(View.GONE);
                    twoExpandableListView.setVisibility(View.VISIBLE);
                    classifyOneListView.setVisibility(View.GONE);
                } else {
                    eList.setVisibility(View.GONE);
                    twoExpandableListView.setVisibility(View.GONE);
                    classifyOneListView.setVisibility(View.VISIBLE);
                }
                initInfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        initInfo();
    }

    private void setSpinnerAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_drop, spinnerList);
        //傳入的參數分別爲 Context , 未選中項的textview , 數據源List
//單獨設置下拉的textview
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        classificationSpinner.setAdapter(arrayAdapter);
    }

    private void initData() {
        list = new ArrayList<>();
        getClassification();

    }

    private void initInfo() {
        getClassification();
//        classificationListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                intent = new Intent(context, AddGoodsActivity.class);
//                intent.putExtra("name", list.get(position).getClass_name());
//                intent.putExtra("id", list.get(position).getId());
//                setResult(1, intent);
//                finish();
//            }
//        });
        /*loadingDialog.show();
        JSONObject json = new JSONObject();
        try {
            json.put("type", 1);
            json.put("keyword",classificationSearchEdit.getText().toString());
            json = Tools.createParameterCode(json);
            HttpUtils.post(context, Common.ALL_CLASSIFY, json, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    Log.e(TAG, "onSuccess: all_classify " + text);
                    Message message = new Message();
                    Gson gson = new Gson();
                    classifyInfo = gson.fromJson(text, ClassifyInfo.class);
                    if (classifyInfo.getStatus() == 1) {
                        message.what = 3;
                    } else {
                        message.what = 4;
                    }
                    handler.sendMessage(message);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
    }

//    private void setClassificationAdapter() {
//        classificationAdapter = new ClassificationAdapter(context, list);
//        classificationListview.setAdapter(classificationAdapter);
//    }

    @OnClick({R.id.title_back, R.id.classification_search_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.classification_search_tv:
                if (TextUtils.isEmpty(classificationSearchEdit.getText().toString())) {
                    Toast.makeText(context, "請輸入搜索的分類名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                kindList.clear();
                childOneList.clear();
                initInfo();
                break;
        }
    }

    private void getClassification() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("keyword", classificationSearchEdit.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
            HttpUtils.post(context, Common.ADD_CLASSIFICATION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    classificationBean = GsonUtils.JsonToBean(text, ClassificationBean.class);
                    Message msg = new Message();
                    if (classificationBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
    }

    /**
     * @author Apathy、恆
     * <p>
     * 點擊子ExpandableListView的子項時，回調本方法，根據下標獲取值來做相應的操作
     */
    @Override
    public void onClickPosition(int parentPosition, int groupPosition,
                                int childPosition) {
        // do something
        String childName = parents.get(parentPosition).getChilds()
                .get(groupPosition).getChildNames().get(childPosition)
                .toString();
//        Toast.makeText(context, "點擊的下標爲： parentPosition=" + parentPosition
//                        + "   groupPosition=" + groupPosition
//                        + "   childPosition=" + childPosition + "\n點擊的是："
//                        + childName, Toast.LENGTH_SHORT).show();
//
//        Log.e(TAG, "onClickPosition: " + classifyInfo.getGoodscate().get(parentPosition).getChildone().get(groupPosition).getChildtwo().get(childPosition).getId());
        intent = new Intent(context, AddGoodsActivity.class);
        intent.putExtra("name", childName);
        intent.putExtra("id", classificationBean.getGoodscate().get(parentPosition).getChild()
                .get(groupPosition).getChild().get(childPosition).getId());
        setResult(1, intent);
        finish();
    }

    /**
     * @author Apathy、恆
     * <p>
     * 展開一項，關閉其他項，保證每次只能展開一項
     */
    @Override
    public void onGroupExpand(int groupPosition) {
        for (int i = 0; i < parents.size(); i++) {
            if (i != groupPosition) {
                eList.collapseGroup(i);
            }/*else{
                parentAdapter.isSelect(groupPosition);
            }*/
        }
    }
}
